package com.rst.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rst.dao.AttendanceDAO;
import com.rst.model.Attendance;
import com.rst.model.Student;

@Service
public class AttendanceService {

	@Autowired
	AttendanceDAO attendanceDAO;
	
	@Autowired 
	StudentService studentService;
	
	public Long saveAttendance(Attendance attendance) {
		return attendanceDAO.saveAttendance(attendance);
	}

	public Attendance getAttendanceById(Long attendanceId) {
		return attendanceDAO.getAttendanceById(attendanceId);
	}

	public String getCalendarByMonth(int month , int year ,Long sectionId) {
		
		GregorianCalendar a = new GregorianCalendar();
		a.set(Calendar.YEAR, year);
		a.set(Calendar.MONTH, (month));
		a.set(Calendar.DAY_OF_MONTH, 1);
		

		int daysInMonth = a.getActualMaximum(Calendar.DAY_OF_MONTH); 
		
		String monthStr = "<table id='register-table'><tbody><tr class='tr-head' id='tr-month'><td class='head-td-name'>Name</td>";
		for(int i = 1;i<=daysInMonth;i++){
			a.set(Calendar.DAY_OF_MONTH, i);
			SimpleDateFormat formatter = new SimpleDateFormat("E");
			monthStr = monthStr + "<td class='head-td-date'><div class='day'>"+
			formatter.format(a.getTime())+"</div> <div class='date'>"+i+"</div></td>";									
		}
		monthStr = monthStr+ "</tr>";	

		List<Student> studentsList =   studentService.getStudentsBySectionId(sectionId);
		for (Student student : studentsList) {
			monthStr = monthStr+ "<tr class='tr-odd td-odd'><td class='td-name'>"+student.getUserDetails().getFirstName()+				
					" "+student.getUserDetails().getLastName()+"</td>";
			for(int j = 1;j<=daysInMonth;j++){
				String dt = j+"-"+month+"-"+year;
				monthStr = monthStr + "<td class='td-mark' id='student-"+student.getId()+"-date-"+dt+"'><a id='"+student.getId()+"|"+dt+"' onclick='displayfancyBox("+student.getId()+","+sectionId+","+dt+");'>P</a></td>";
			}
			monthStr = monthStr+ "</tr>";
		}
		monthStr = monthStr+ "</tbody></table>";		
		return monthStr;
	}
	
}
